package com.red.battleworm.model {
	import flash.utils.ByteArray;	
	import flash.events.ProgressEvent;	
	import flash.events.SecurityErrorEvent;	
	import flash.events.IOErrorEvent;	
	import flash.events.Event;	
	import flash.events.EventDispatcher;	
	import flash.events.IEventDispatcher;	
	
	import com.red.net.SocketEvent;	
	
	import flash.net.Socket;
	
	import org.puremvc.as3.patterns.proxy.Proxy;

	/**
	 * @author zhangs
	 */
	public class NetProxy extends Proxy implements IEventDispatcher {
		private var socket : Socket;
		private var dispatcher : EventDispatcher;
		
		public function NetProxy(server : String, port : uint) {
			super("NetProxy", null);
			
			socket.addEventListener(Event.CLOSE, closeHandler);
	        socket.addEventListener(Event.CONNECT, connectHandler);
	        socket.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
	        socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
			socket.addEventListener(ProgressEvent.SOCKET_DATA, receiveData);
			
			dispatcher = new EventDispatcher(this);

			socket.connect(server, port);
		}
		
		public function sendData(data : Object):void {
			var ba : ByteArray = new ByteArray();
			ba.writeMultiByte(data.toString(), "UTF-8");
			socket.writeBytes(ba);
			socket.flush();
		}
		
		public function sendAndListen(data : Object, fun : Function) : void {
			this.addEventListener(SocketEvent.SOCKET_DATA, fun);
			sendData(data);
		}
		
		private function receiveData(e : SocketEvent) : void{
			var ba : ByteArray = new ByteArray();
			socket.readBytes(ba);
			
			var event : SocketEvent = new SocketEvent();
			event.data = ba.toString();
			dispatchEvent(event);
		}
		
	    private function closeHandler(event:Event):void {
	        
		}
	
	    private function connectHandler(event:Event):void {
	        
	    }
	
	    private function ioErrorHandler(event:IOErrorEvent):void {
	        
	    }
	
	    private function securityErrorHandler(event:SecurityErrorEvent):void {
		}
		
		public function dispatchEvent(event : Event) : Boolean {
			return dispatcher.dispatchEvent(event);
		}
		
		public function hasEventListener(type : String) : Boolean {
			return dispatcher.hasEventListener(type);
		}
		
		public function willTrigger(type : String) : Boolean {
			return dispatcher.willTrigger(type);
		}
		
		public function removeEventListener(type : String, listener : Function, useCapture : Boolean = false) : void {
			dispatcher.removeEventListener(type, listener, useCapture);
		}
		
		public function addEventListener(type : String, listener : Function, useCapture : Boolean = false, priority : int = 0, useWeakReference : Boolean = false) : void {
			dispatcher.addEventListener(type, listener, useCapture, priority, useWeakReference);
		}
	}
}
